package com.ww.aviator.func;

import com.googlecode.aviator.exception.FunctionNotFoundException;
import com.googlecode.aviator.runtime.RuntimeUtils;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.*;

import java.util.Map;

public class SeqMapFunction extends AbstractFunction {

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
        Object first = arg1.getValue(env);
        AviatorFunction fun = FunctionUtils.getFunction(arg2, env, 1);
        if (null == fun) {
            throw new FunctionNotFoundException("函数没找到" + ((AviatorJavaType) arg2).getName());
        }
        if (null == first) {
            throw new NullPointerException("null seq");
        }
        Sequence seq = RuntimeUtils.seq(first, env);
        Collector collector = seq.newCollector(seq.hintSize());
        for (Object obj : seq) {
            collector.add(fun.call(env, AviatorRuntimeJavaType.valueOf(obj)).getValue(env));
        }
        return AviatorRuntimeJavaType.valueOf(collector.getRawContainer());
    }

    /**
     * Get the function name
     *
     * @return
     */
    @Override
    public String getName() {
        return "map";
    }
}
